package com.heima.wemedia.service.impl;


import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.injector.methods.SelectList;
import com.baomidou.mybatisplus.core.injector.methods.SelectOne;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.constants.WmNewsMessageConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.admin.dtos.NewsAuthDto;
import com.heima.model.admin.pojos.ApUserRealname;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmNewsVo;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.core.util.JsonUtils;
import org.jsoup.helper.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class WmNewsServiceImpl  extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private WmUserMapper wmUserMapper;

    /**
     * 用来调用延迟队列
     */
    @Autowired
    private WmNewsTaskService wmNewsTaskService;

    @Autowired
    private KafkaTemplate kafkaTemplate;


    @Override
    public ResponseResult findAll(WmNewsPageReqDto wmNewsPageReqDto) {

        //参数校验
        wmNewsPageReqDto.checkParam();

        //分页查询
        IPage page = new Page<>(wmNewsPageReqDto.getPage(), wmNewsPageReqDto.getSize());
        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        //关键字查询:模糊查询
        if (StringUtils.isNotBlank(wmNewsPageReqDto.getKeyword())) {
            lambdaQueryWrapper.like(WmNews::getTitle, wmNewsPageReqDto.getKeyword());
        }

        //状态查询
        if (wmNewsPageReqDto.getStatus() != null) {
            lambdaQueryWrapper.eq(WmNews::getStatus, wmNewsPageReqDto.getStatus());
        }

        //日期查询
        if (wmNewsPageReqDto.getBeginPubDate() != null && wmNewsPageReqDto.getEndPubDate() != null) {
            lambdaQueryWrapper.between(WmNews::getPublishTime, wmNewsPageReqDto.getBeginPubDate(), wmNewsPageReqDto.getEndPubDate());
        }

        //频道查询
        if (wmNewsPageReqDto.getChannelId() != null) {
            lambdaQueryWrapper.eq(WmNews::getChannelId, wmNewsPageReqDto.getChannelId());

        }
        //查询当前登录用户的文章
        lambdaQueryWrapper.eq(WmNews::getUserId, WmThreadLocalUtil.getUser().getId());


        page = page(page, lambdaQueryWrapper);

        ResponseResult result = new PageResponseResult(wmNewsPageReqDto.getPage(), wmNewsPageReqDto.getSize(), (int) page.getTotal());

        result.setData(page.getRecords());

        return result;
    }


    /**
     * 发布修改文章或保存为草稿
     *
     * @param wmNewsDto
     * @return
     */
    @Override
    public ResponseResult submitNews(WmNewsDto wmNewsDto) {
        //0.条件判断
        if (wmNewsDto == null && wmNewsDto.getContent() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //1.保存或修改文章
        WmNews wmNews = new WmNews();

        BeanUtils.copyProperties(wmNewsDto, wmNews);

        if (wmNewsDto.getImages() != null && wmNewsDto.getImages().size() > 0) {
            //TODO
            String imageUrl = StringUtil.join(wmNewsDto.getImages(), ",");
            wmNews.setImages(imageUrl);
        }
        //因为WmNews的type没有-1
        if (wmNewsDto.getType() == -1) {
            wmNews.setType(null);
        }
        //保存或修改文章（也有草稿）
        saveOrUpdateWmNews(wmNews);


        //2.判断保存或修改后的是否为草稿  如果为草稿结束当前方法，之后的就不执行了
        if (wmNews.getStatus().equals(WmNews.Status.NORMAL.getCode())) {//状态0是草稿
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }


        //3.不是草稿，保存文章内容图片与素材的关系
        //注意：WmNewsMaterialMapper中的saveRelations中的 materialIds接收的是素材id组成的List集合
        //现在能获取   wmNewsDto.getContent(),要提取内容中的图片信息组成List<String>
        List<String> materials = ectractUrlInfo(wmNewsDto.getContent());

        //使用处理文章内容图片与素材的关系的通用方法
        //传入素材url集合和文章id
        saveRelativeInfoForContent(materials, wmNews.getId());


        //4.不是草稿，保存文章封面图片与素材的关系，如果当前布局是自动，需要匹配封面图片
        /**
         * materials 是内容图片
         * wmNewsDto 用来获取封面图片
         * wmNews 用来更新操作
         */
        saveRelativeInfoForCover(wmNewsDto, wmNews, materials);


        //这步进行文章审核
//        wmNewsAutoScanService.autoScanWmNews(wmNews.getId());

        //调用延迟队列，上面的文章审核注释掉(文章审核不再在这里进行调用了，而是通过定时任务)
        wmNewsTaskService.addNewsToTask(wmNews.getId(), wmNews.getPublishTime());

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    /**
     * 保存或修改文章（草稿）
     *
     * @param wmNews
     */
    private void saveOrUpdateWmNews(WmNews wmNews) {
        //补全属性
        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable((short) 1);//默认上架

        //如果id为null,就保存文章（草稿）新增操作
        if (wmNews.getId() == null) {
            save(wmNews);
        } else {
            //Id不为Null，就是修改操作
            //先删除关联关系
            LambdaQueryWrapper<WmNewsMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            LambdaQueryWrapper<WmNewsMaterial> eq = lambdaQueryWrapper.eq(WmNewsMaterial::getNewsId, wmNews.getId());
            wmNewsMaterialMapper.delete(eq);

            //再修改
            updateById(wmNews);
        }
    }

    /**
     * 获取文章内容content中的图片信息
     * type":"image"
     * "value":"http://192.168.200.130/group1/M00/00/00/wKjIgl5swbGATaSAAAEPfZfx6Iw790.png
     *
     * @param content
     * @return
     */
    private List<String> ectractUrlInfo(String content) {
        //创建一个用户存储图片信息的集合
        List<String> materials = new ArrayList<>();
        //TODO
        //内容的json字符串转为Map类型
        List<Map> maps = JSON.parseArray(content, Map.class);
        for (Map map : maps) {
            if (map.get("type").equals("image")) {
                materials.add((String) map.get("value"));
            }
        }
        return materials;
    }

    /**
     * 处理文章内容图片与素材的关系
     *
     * @param materials
     * @param newsId
     */
    private void saveRelativeInfoForContent(List<String> materials, Integer newsId) {
        //不是草稿，保存文章内容图片与素材的关系
        saveRelativeInfo(materials, newsId, WemediaConstants.WM_CONTENT_REFERENCE);//type为内容引用
    }

    /**
     * 通用方法：保存文章内容或封面 的图片与素材的关系
     *
     * @param materials
     * @param newsId
     * @param type
     */
    private void saveRelativeInfo(List<String> materials, Integer newsId, Short type) {

        if (materials != null && !materials.isEmpty()) {
            //通过素材图片的url查询素材的id
            //构建查询条件
            LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            LambdaQueryWrapper<WmMaterial> in = lambdaQueryWrapper.in(WmMaterial::getUrl, materials);

            List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(in);

            //判断素材是否有效
            if (wmMaterials == null || wmMaterials.size() == 0) {
                //手动抛出异常   第一个功能：能够提示调用者素材失效了，第二个功能，进行数据的回滚
                throw new CustomException(AppHttpCodeEnum.MATERIASL_REFERENCE_FAIL);
            }
            if (materials.size() != wmMaterials.size()) {
                throw new CustomException(AppHttpCodeEnum.MATERIASL_REFERENCE_FAIL);
            }

            //将素材中的id组成集合
            List<Integer> collect = wmMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());

            //进行批量保存
            wmNewsMaterialMapper.saveRelations(collect, newsId, type);
        }

    }

    /**
     * 第一个功能：如果当前封面类型为自动，则设置封面类型的数据
     * 匹配规则：
     * 1，如果内容图片大于等于1，小于3  单图  type 1
     * 2，如果内容图片大于等于3  多图  type 3
     * 3，如果内容没有图片，无图  type 0
     * 第二个功能：保存封面图片与素材的关系
     *
     * @param wmNewsDto
     * @param wmNews
     * @param materials
     */
    private void saveRelativeInfoForCover(WmNewsDto wmNewsDto, WmNews wmNews, List<String> materials) {
        //封面图片
        List<String> images = wmNewsDto.getImages();
        //如果封面类型为自动的
        if (wmNewsDto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            if (materials.size() > 3) {
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                images = materials.stream().limit(3).collect(Collectors.toList());
            } else if (materials.size() >= 1 && materials.size() < 3) {
                wmNews.setType(WemediaConstants.WM_COVER_REFERENCE);
                images = materials.stream().limit(1).collect(Collectors.toList());
            } else {
                wmNews.setType(WemediaConstants.WM_CONTENT_REFERENCE);
            }
        }
        //其他的就直接保存就行了
        //先更新图片
        //集合转String
        String join = StringUtil.join(images, ",");
        wmNews.setImages(join);
        updateById(wmNews);

        //保存关系
        /**
         * 参数一：传images
         *
         */
        if (images != null && images.size() > 0) {
            saveRelativeInfo(images, wmNews.getUserId(), WemediaConstants.WM_COVER_REFERENCE);
        }


    }


    /**
     * 文章的上下架
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        //1.检查参数
        if (dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }

        //3.判断文章是否已发布
        if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "当前文章不是发布状态，不能上下架");
        }

        //4.修改文章enable  0 下架  1 上架
        if (dto.getEnable() != null && dto.getEnable() > -1 && dto.getEnable() < 2) {
            wmNews.setEnable(dto.getEnable());
            updateById(wmNews);

            //发送消息，通知article端修改文章配置
            if (wmNews.getArticleId() != null) {
                HashMap<String, Object> hashMap = new HashMap<>();
                hashMap.put("articleId", wmNews.getArticleId());
                hashMap.put("enable", dto.getEnable());
                kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC, JSON.toJSONString(hashMap));

            }

        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 自媒体文章审核-查询文章列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(NewsAuthDto dto) {
        //校验参数
        if (dto == null || dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();

        //2.分页查询+count查询
        dto.setPage((dto.getPage() - 1) * dto.getSize());
        List<WmNewsVo> wmNewsVoList = wmNewsMapper.findListAndPage(dto);
        int count = wmNewsMapper.findListCount(dto);

        //3.结果返回
        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), count);
        responseResult.setData(wmNewsVoList);
        return responseResult;
    }

    /**
     * 自媒体文章人工审核-查询文章详情
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult findWmNewsVo(Integer id) {
        //1.检查参数
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章信息
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //3.查询用户信息
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());

        //4.封装vo返回
        WmNewsVo vo = new WmNewsVo();

        //属性拷贝
        BeanUtils.copyProperties(wmNews, vo);
        if (wmUser != null) {
            vo.setAuthorName(wmUser.getName());
        }

        return ResponseResult.okResult(vo);
    }

    /**
     * 自媒体文章人工审核-文章审核
     *
     * @param dto
     * @param status
     * @return
     */
    @Override
    public ResponseResult updateStatus(NewsAuthDto dto, Short status) {
        //1.检查参数
        if (dto == null || dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章信息
        WmNews wmNews = getById(dto.getId());
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //3.修改文章的状态
        wmNews.setStatus(status);
        if (StringUtils.isNotBlank(dto.getMsg())) {
            wmNews.setReason(dto.getMsg());
        }
        updateById(wmNews);

        //审核成功，则需要创建app端文章数据，并修改自媒体文章
        if (status.equals(WemediaConstants.WM_NEWS_AUTH_PASS)) {
            //创建app端文章数据
            ResponseResult responseResult = wmNewsAutoScanService.saveAppArticle(wmNews);
            if (responseResult.getCode().equals(200)) {
                wmNews.setArticleId((Long) responseResult.getData());
                wmNews.setStatus(WmNews.Status.PUBLISHED.getCode());
                updateById(wmNews);
            }
        }
        //4.返回
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

}
